package org.jogdiary2011.service;

import java.util.List;
import java.util.Map;

import org.jogdiary2011.meta.PersonMeta;
import org.jogdiary2011.model.Person;
import org.slim3.datastore.Datastore;
import org.slim3.util.BeanUtil;

import com.google.appengine.api.datastore.Key;

public class PersonService {

    private PersonMeta personMeta = new PersonMeta();

    /**
     * Put model to Datastore. <br/>
     * 
     * @param requestMap
     * @return Person
     */
    public Person insert(Map<String, Object> requestMap) {
        Person person = new Person();
        BeanUtil.copy(requestMap, person);

        // Transaction tx = Datastore.beginTransaction();
        // Datastore.put(tx, person);
        // tx.commit();

        Datastore.put(person);
        System.out.println(person.getKey());
        System.out.println(person.getNickName());
        return person;
    }

    public List<Person> findAll() {
        return Datastore
            .query(personMeta)
            .sort(personMeta.firstName.asc)
            .asList();

    }

    public Person getByNickName(String nickName) {
        // TODO Auto-generated method stub
        return Datastore.query(personMeta).filter(
            personMeta.nickName.equal(nickName)).asSingle();
    }

    public Person get(Key key) {
        return Datastore.get(personMeta, key);
    }

    public Person get(Key key, Long version) {
        return Datastore.get(personMeta, key, version);
    }

    public Person update(Key key, Long version, Map<String, Object> requestMap) {
        
        Person person = get(key, version);
        BeanUtil.copy(requestMap, person);
        Datastore.put(person);
        return person;
    }
}
